package com.github.niefy.common.exception;

import com.github.niefy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.PropertyKey;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 获取错误码对应错误信息，idea辅助提示
 */
@Slf4j
public class ErrorMessage {
    private static final String BUNDLE_FQN = "error.error_code";
    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_FQN, Locale.SIMPLIFIED_CHINESE);

    /**
     * 用于接口返回响应体
     * */
    public static R messageToR(@PropertyKey(resourceBundle = BUNDLE_FQN) String key, Object... params) {
        if (RESOURCE_BUNDLE.containsKey(key)) {
            String value = RESOURCE_BUNDLE.getString(key);
            final FormattingTuple tuple = MessageFormatter.arrayFormat(value, params);
            var r = R.error(key, tuple.getMessage());
            log.info(r.toString());
            return r;
        } else {
            return R.error(key,MessageFormatter.arrayFormat(key, params).getMessage());
        }
    }

    /**
     * 用于接口引发异常返回响应体,异常堆栈信息打印到日志文件
     * */
    public static R exceptionMsgToR(@PropertyKey(resourceBundle = BUNDLE_FQN) String key, Exception e, Object... params) {
        log.error("错误堆栈信息：", e);
        if (RESOURCE_BUNDLE.containsKey(key)) {
            String value = RESOURCE_BUNDLE.getString(key);
            final FormattingTuple tuple = MessageFormatter.arrayFormat(value, params);
            //log.error(R.error(key, tuple.getMessage()).toString());
            return R.error(key, tuple.getMessage());
        } else {
            return R.error(key,MessageFormatter.arrayFormat(key, params).getMessage());
        }
    }

    /**
     * 用于直接打印日志
     * @param key
     * @param params
     * @return
     */
    public static String messageToString(@PropertyKey(resourceBundle = BUNDLE_FQN) String key, Object... params) {
        if (RESOURCE_BUNDLE.containsKey(key)) {
            String value = RESOURCE_BUNDLE.getString(key);
            final FormattingTuple tuple = MessageFormatter.arrayFormat(value, params);
            return key + " - " + tuple.getMessage();
        } else {
            return MessageFormatter.arrayFormat(key, params).getMessage();
        }
    }
}
